﻿using Magicodes.WeiChat.Data.Models;
using Magicodes.WeChat.SDK;
using Magicodes.WeiChat.Infrastructure.Cache;
using Magicodes.WeiChat.Models;
using Magicodes.WeiChat.Unity;
using Magicodes.WeiChat.WeChatHelper.Task;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.Analysis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Magicodes.ECharts;
using Magicodes.ECharts.Axis;
using Magicodes.ECharts.CommonDefinitions;
using Magicodes.ECharts.Components.Title;
using Magicodes.ECharts.Mvc.Results;
using Magicodes.ECharts.Series;
using Magicodes.ECharts.Series.Mark;
using Magicodes.ECharts.ValueTypes;
using Magicodes.ECharts.Mvc;
using Magicodes.Mvc.RoleMenuFilter;
using Magicodes.WeChat.SDK.Apis.Statistics;

namespace Magicodes.WeiChat.Controllers
{
    [Authorize]
    [RoleMenuFilter("仪表盘", "{99A31780-B8C5-4AF6-ACBB-4598C8A60661}", "Admin",
     iconCls: "fa fa-dashboard", orderNo: -100)]
    public class HomeController : TenantBaseController<WeiChat.Data.Models.WeiChat_App>
    {
        private readonly StatisticsApi api = WeChatApisContext.Current.StatisticsApi;
        //
        // GET: /Home/
        [RoleMenuFilter("首页", "{79FD819B-976E-441C-AF57-DB9AB963BBDD}", "Admin",
                     url: "/", parentId: "{99A31780-B8C5-4AF6-ACBB-4598C8A60661}", iconCls: "fa fa-home")]
        public ActionResult Index()
        {
            //如果没有配置租户信息，则必须前去配置
            if (!HasConfigWeiChat && IsSystemIenant)
            {
                return RedirectToAction("WeiChatAppConfig", "Account_Tenant", new { area = "SystemAdmin", tenantId = TenantId });
            }
            #region 获取最新关注的5位用户
            var last5Users = GetLast5Users();
            ViewBag.Last5Users = last5Users;
            #endregion


            var cache = Magicodes.WeiChat.Infrastructure.Cache.CacheManager.Current;
            #region 累积关注数
            {
                var value = cache.GetByTenant<int>("UserSummaryCount");
                if (value == default(int))
                {
                    var beginDate = DateTime.Now.AddDays(-5);
                    var endDate = DateTime.Now.AddDays(-1);
                    var getCumulateResult = api.GetStatisticsInfo<UserCumulateAnalyisResult>(beginDate, endDate,
                        "getusercumulate");
                    if (getCumulateResult.IsSuccess())
                    {
                        getCumulateResult.CumulateList.ForEach(item => { value += (int)item.CumulateUser; });
                    }

                }
                cache.AddOrUpdateByTenant("UserCumulateCount", value, TimeSpan.FromHours(12));
                ViewBag.UserSummaryCount = value;
            }

            #endregion


            #region 取消关注数、新关注数、净增用户数
            {
                //取消关注数
                var cancelUserCount = cache.GetByTenant<int>("CancelUserCount");
                //新关注数
                var newUserCount = cache.GetByTenant<int>("NewUserCount");
                //净增用户数
                var growUserCount = cache.GetByTenant<int>("GrowUserCount");
                if (newUserCount == default(int))
                {
                    var beginDate = DateTime.Now.AddDays(-5);
                    var endDate = DateTime.Now.AddDays(-1);
                    var apiResult = api.GetStatisticsInfo<UserSummaryAnalyisResult>(beginDate, endDate,
                        "getusersummary");

                    if (apiResult.IsSuccess() && apiResult.SersummaryList != null)
                    {
                        apiResult.SersummaryList.ForEach(item => {
                            cancelUserCount += (int)item.CancelUser;
                            newUserCount += (int)item.NewUser;
                        });
                        growUserCount = newUserCount - cancelUserCount;
                        
                        cache.AddOrUpdateByTenant("CancelUserCount", cancelUserCount, TimeSpan.FromHours(12));
                        cache.AddOrUpdateByTenant("NewUserCount", newUserCount, TimeSpan.FromHours(12));
                        cache.AddOrUpdateByTenant("GrowUserCount", growUserCount, TimeSpan.FromHours(12));
                    }
                }
                //取消关注数
                ViewBag.CancelUserCount = cancelUserCount;
                //新关注数
                ViewBag.NewUserCount = newUserCount;
                //净增用户数
                ViewBag.GrowUserCount = growUserCount;
            }

            #endregion

            ViewBag.ChartEnable = false;
            //如果粉丝量大于20万，禁用部分图表 
            if (cache.GetByTenant<int>("UserSummaryCount") < 200000 && db.WeiChat_Users.Count() < 200000)
                ViewBag.ChartEnable = true;
            return View();
        }


        [HttpGet]
        public JavaScriptJsonResult UserTimeChart()
        {
            var seriesData = new List<object>();
            var xAxisData = new List<object>();
            for (int i = 0; i < 6; i++)
            {
                var currentTime = DateTime.Now.AddMonths(-i);
                xAxisData.Add(currentTime.ToString("MM月"));
                seriesData.Add(db.WeiChat_Users.AsNoTracking().Count(p => p.SubscribeTime.Year == currentTime.Year && p.SubscribeTime.Month == currentTime.Month).ToString());
            }
            var chartOptions = new EChartsOption()
            {
                Title = new Title("半年公众号关注变化") { Left = new AlignValue(Align.center) },
                Series = new Series[]
                {
                    new LineSeries()
                    {
                        Name = "半年公众号关注变化",
                        Data = seriesData,
                        Smooth = true,
                        MarkPoint=new MarkPoint()
                        {
                            Data=new List<MarkData>()
                            {
                                new MarkData() {Type=MarkPointDataTypes.max,Name="最大值" },
                                new MarkData() {Type=MarkPointDataTypes.min,Name="最小值" },
                            }
                        },
                        MarkLine=new MarkLine()
                        {
                            Data=new List<MarkData>()
                            {
                                new MarkData() { Type=MarkPointDataTypes.average,Name="平均值"}
                            }
                        }
                    }
                },
                XAxis = new XAxis[1] { new XAxis { Type = AxisTypes.category, Data = xAxisData } },
                YAxis = new YAxis[1] { new YAxis { Type = AxisTypes.value, AxisLabel = new Label() { Formatter = "{value} 人" } } },
            };
            return this.ToEChartResult(chartOptions);
        }
        /// <summary>
        /// 获取粉丝分布统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JavaScriptJsonResult UserAreaChart()
        {
            var provinces = db.WeiChat_Users.AsNoTracking().Where(p => p.Subscribe).Select(p => p.Province).Distinct().ToList().Select(p => (object)p).ToList();
            var valueList = new List<object>();
            foreach (var item in provinces)
            {
                valueList.Add(db.WeiChat_Users.Count(p => p.Subscribe && p.Province == item).ToString());
            }
            var chartOptions = new EChartsOption()
            {
                Title = new Title("粉丝分布统计图") { Left = new AlignValue(Align.center) },
                Series = new Series[]
                {
                    new BarSeries()
                    {
                        Name = "粉丝分布",
                        Data = valueList,
                        MarkPoint=new MarkPoint()
                        {
                            Data=new List<MarkData>()
                            {
                                new MarkData() {Type=MarkPointDataTypes.max,Name="最大值" },
                                new MarkData() {Type=MarkPointDataTypes.min,Name="最小值" },
                            }
                        },
                        MarkLine=new MarkLine()
                        {
                            Data=new List<MarkData>()
                            {
                                new MarkData() { Type=MarkPointDataTypes.average,Name="平均值"}
                            }
                        }
                    }
                },
                XAxis = new XAxis[1] { new XAxis { Type = AxisTypes.category, Data = provinces } },
                YAxis = new YAxis[1] { new YAxis { Type = AxisTypes.value } },

            };
            return this.ToEChartResult(chartOptions);
        }

        private List<HomeUserViewModel> GetLast5Users()
        {
            var styles = new string[] { "success", "info", "primary", "default", "primary" };
            var last5Users = db.WeiChat_Users.Where(p => p.Subscribe).OrderByDescending(p => p.SubscribeTime).Take(5).ToList().Select(p => new HomeUserViewModel
            {
                NickName = p.NickName,
                SubscribeTime = p.SubscribeTime.ToString("MM-dd HH:mm:ss"),
            }).ToList();
            for (int i = 0; i < last5Users.Count; i++)
            {
                last5Users[i].Style = styles[i];
            }
            return last5Users;
        }

        /// <summary>
        /// 500
        /// </summary>
        /// <returns></returns>
        [Route("Error")]
        public ActionResult Error()
        {
            return View();
        }
        /// <summary>
        /// 404
        /// </summary>
        /// <returns></returns>
        [Route("NotFoundError")]
        public ActionResult NotFoundError()
        {
            return View();
        }
    }
}